package nil.ed.livechat.timeshift.utils.m3u8;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * @author delin10
 * @since 2020/6/26
 **/
public class NetUtils {

    public static byte[] getAllBytes(String url) {
        try (CloseableHttpClient client = HttpClients.createDefault()){
            HttpGet get = new HttpGet(url);
            HttpResponse response = client.execute(get);
            String lengthStr = Optional.ofNullable(response.getFirstHeader("Content-Length"))
                    .map(Header::getValue)
                    .orElse("-1");
            int length = Integer.parseInt(lengthStr);
            InputStream inputStream = response.getEntity().getContent();
            if (response.getStatusLine().getStatusCode() != 200) {
                return new byte[0];
            }
            byte[] result;
            if (length != -1) {
                result = new byte[length];
                int n = inputStream.read(result);
                if (n != length) {
                    return new byte[0];
                }
            } else {
                List<byte[]> buffers = new LinkedList<>();
                byte[] tmp = new byte[1024];
                int count = 0;
                int n;
                while ((n = inputStream.read(tmp)) > 0) {
                    buffers.add(tmp);
                    count += n;
                }

                Iterator<byte[]> it = buffers.iterator();
                result = new byte[count];
                int used = 0;
                while (it.hasNext()) {
                    byte[] bs = it.next();
                    if (it.hasNext()) {
                        System.arraycopy(bs, 0, result, used, bs.length);
                        used += bs.length;
                    } else {
                        System.arraycopy(bs, 0, result, used, count - used);
                    }

                }
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public static void uploadFile() {

    }

}
